package org.example.project.common.error.handle;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author wenxy
 * @date 2020/11/2
 */
@Component
@Aspect
@ConditionalOnProperty(value = "yundasys.vienna.common.mdc-log.enable", havingValue = "true")
public class MdcLogAspect {

    /**
     * 启停切面
     * 通过属性有2种方式，
     * 1. 是通过属性@ConditionalOnProperty，控制切面bean
     * 2. 增加变量
     */
    @Value("${yundasys.vienna.common.mdc-log.enable:false}")
    boolean enable;

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController)")
    public void pointCut() {
    }

    @Around(value = "pointCut()")
    public Object mdcLogAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!isEnable()) {
            return joinPoint.proceed();
        }

        MDC.put("traceId", UUID.randomUUID().toString());
        try {
            return joinPoint.proceed();
        } finally {
            MDC.clear();
        }
    }

    boolean isEnable() {
        return enable;
    }

}
